var PATH_PREFIX ="";
var PATH ="";
var tableIndexs = "1";
/**
* 获取本周、本季度、本月、上月的开始日期、结束日期
*/
var now = new Date(); //当前日期 
var nowDayOfWeek = now.getDay(); //今天本周的第几天 
var nowDay = now.getDate(); //当前日 
var nowMonth = now.getMonth(); //当前月 
var nowYear = now.getFullYear(); //当前年 
nowYear += (nowYear < 2000) ? 1900 : 0; //

function setPathPrefix(path){
	PATH_PREFIX =  path;
}
function setPath(path){
	PATH = path;
}
$(function() {
	 initChoose('todoStatus');
	// 给select2组件加载样式
	WASP_WIDGET.initializeSelectStyle();
	//初始化日期
	//WASP_WIDGET.triggerDateStyleWithYMD("#q-reportTime");
	WASP_WIDGET.triggerDateRangeStyle("q-reportTime");
	WASP_WIDGET.triggerDateRangeStyle("q-uploadTime");
	WASP_WIDGET.triggerDateRangeStyle("q-endTime");
	// 注册清空事件
    WASP_WIDGET.registerResetClearEvent();
    //初始化事件
	init();
	//选中样式
	chosenStyle();
	//initMultipleSelectType();
    
});
// 连接跳转过来也要选中样式
function chosenStyle(){
	var estTab = window.parent.document.getElementById("estTab");
	window.parent.pageApp.changeLocation($(estTab));
//    $(estTab).addClass('active');
//    var estimate = window.parent.document.getElementsByClassName('estimate');
//    $(estimate).removeClass('active');
}

var $estimateList = $('#estimateList');

var ESTIMATE_INFO = {
	/*estimateUpload : function(type,prjsname,reportTime,prjCode,estimateId){
		//var url = PATH_PREFIX + "estimateUpload.do?type="+type+"&&prjsname="+prjsname+"&&reportTime="+reportTime+"&&prjCode="+prjCode+"&&estimateId="+estimateId;
		var url = "/business/myHome/todoAndOutput/toEndFileUploadView4Biz.do?bizType=ESTIMATE&bizId="+estimateId
		window.open(url);
		
	},*/
	estimateUpload : function(estimateId){
		//var url = PATH_PREFIX + "estimateUpload.do?type="+type+"&&prjsname="+prjsname+"&&reportTime="+reportTime+"&&prjCode="+prjCode+"&&estimateId="+estimateId;
		var url = PATH + "/business/myHome/todoAndOutput/toEndFileUploadView4Biz.do?bizType=ESTIMATE&bizId="+estimateId;
		window.open(url);
		
	},
	batchDownEstimate : function(type){
		var ids = $estimateList.jqGrid('getGridParam', 'selarrrow');//选择多选
		var estimateIds = "";
		var actionUrl = "";
		var fileType = "";
		var message = "";
		if(ids.length == 0){
			ctools.alert('请至少选择一条数据!',"","warning");
			return;
		}
		
		for(var i = 0; i<ids.length;i++){
			var rowData = $estimateList.jqGrid('getRowData', ids[i]);
			var prdCode = rowData.prdCode;
			var prdsname = rowData.prdsname;
			var estimateId = rowData.estimateId;
			var todoStatus = rowData.todoStatus;
			if("ESTIMATE_DATA" == type){
				//估值材料判断
				if(!('C' == todoStatus || 'S' == todoStatus || 'E' == todoStatus)){
					ctools.alert('选中的数据,有待办状态不是材料已上传,材料已确认,已完成的数据!',"","warning");
					return;
				}
				
			}else if("ESTIMATE_FILE" == type){
				//估值文件判断
				if('E' != todoStatus){
					ctools.alert('选中的数据,有待办状态不是已完成的数据！',"","warning");
					return;
				}
			}
			estimateIds += estimateId + ",";
			
		}
		if("ESTIMATE_FILE" == type){
			actionUrl = PATH + "/business/myHome/todoAndOutput/batchEndFileDownload4Biz.do?bizType=ESTIMATE&bizId="+estimateIds;
			fileType = "output";
			message = "选中的数据里有未上传估值文件!";
		}else if ("ESTIMATE_DATA" == type){
			actionUrl = PATH + "/business/myHome/todoAndOutput/batchTodoFileDownload4Biz.do?bizType=ESTIMATE&bizId="+estimateIds;
			fileType = "input";
			message = "选中的数据里有未上传估值材料!";
		}
		$.ajax({
			type:"POST",
			url: PATH +"business/myHome/todoAndOutput/validateExistsFile.do",
			data:{"bizType" : 'ESTIMATE',
				  "bizId" : estimateIds,
				  "fileType":fileType
				},
			cache:false,
			dataType:"json",
			success:function(data){
				var a = data;
				if(data.success){
					window.location = actionUrl;
				}else {
					ctools.alert(message,"","warning");
				}
			}
		});
	},
	attachDownload : function(estimateId,type){
		var fileType = "";
		var actionUrl = "";
		var message = "";
		if("ESTIMATE_FILE" == type){
			actionUrl = PATH + "/business/myHome/todoAndOutput/batchEndFileDownload4Biz.do?bizType=ESTIMATE&bizId="+estimateId;
			fileType = "output";
			message = "选中的数据里有未上传估值文件!";
		}else if ("ESTIMATE_DATA" == type){
			actionUrl = PATH + "/business/myHome/todoAndOutput/batchTodoFileDownload4Biz.do?bizType=ESTIMATE&bizId="+estimateId;
			fileType = "input";
			message = "选中的数据里有未上传估值材料!";
		}
		$.ajax({
			type:"POST",
			url: PATH +"business/myHome/todoAndOutput/validateExistsFile.do",
			data:{"bizType" : 'ESTIMATE',
				  "bizId" : estimateId,
				  "fileType":fileType
				},
			cache:false,
			dataType:"json",
			success:function(data){
				if(data.success){
					window.location = actionUrl;
				}else {
					ctools.alert(message,"","warning");
				}
			}
		});
		//var actionUrl = PATH + "/business/myHome/todoAndOutput/batchTodoFileDownload4Biz.do?bizType=ESTIMATE&bizId="+estimateId;
		//var actionUrl = encodeURI(PATH_PREFIX+"/batchDownAttach.do?estimateIds="+ estimateId+"&esstimateType="+type+"&isBatch=N");
	}
};

function init(){
	var postData = {};
	var esstimateType = $('#esstimateType').val();
	var esstimateName = $('#esstimateName').val();
	if(esstimateType == 'ESTIMATE_DATA'){
		if(esstimateName == '已上传'){
			$('#q-isEstimateData').val('1').trigger("change");
		}
		if(esstimateName == '未上传'){
			$('#q-isEstimateData').val('0').trigger("change");
		}
		postData = {'sp[isEstimateData]':$('#q-isEstimateData').val()};
	}
	
	if(esstimateType == 'ESTIMATE_FILE'){
		if(esstimateName == '已上传'){
			$('#q-isEstimateFile').val('1').trigger("change");
		}
		if(esstimateName == '未上传'){
			$('#q-isEstimateFile').val('0').trigger("change");
		}
		postData = {'sp[isEstimateFile]':$('#q-isEstimateFile').val()};
	}
	console.log(postData);
	initTableGrid(postData);
}
function initTableGrid(postData) {
	$estimateList.jqGrid({
		url:PATH_PREFIX+'estimateInfoListPage.do',
		//caption:'估值表<button type="button" class="btn btn-default btn-sm btn-small btn-fullscreen" title="" tabindex="-1"><i class="fa fa-arrows-alt icon-fullscreen"></i></button>',  
		datatype: "local",
		colNames:["估值表ID","产品名称","产品代码","产品编码","估值日期",'',"待办状态","材料上传日期","产出上传日期","材料是否上传","操作"],
		colModel:[ { name: 'estimateId', index: 'estimateId', key: true, hidden : true },  
		            { name: 'prjsname', index: 'prdsname', width: 20, resizable: true, sortable: false },
		            { name: 'outerId', index: 'outerId', width: 20, resizable: true, sortable: false},
		            { name: 'prjCode', index: 'prdCode', width: 20, resizable: true, sortable: false, hidden : true},
		            { name: 'reportTime', index: 'reportTime', width: 20, resizable: true, sortable: false },
		            { name: 'todoStatus', index: 'todoStatus', width: 20, resizable: true, sortable: false, hidden : true },
		            { name: 'todoStatusName', index: 'todoStatusName', width: 20, resizable: true, sortable: false },
		            { name: 'uploadTime', index: 'uploadTime', width: 20, resizable: true, sortable: false },
		            { name: 'endTime', index: 'endTime', width: 20, resizable: true, sortable: false },
		            { name: 'noFile', index: 'noFile', width: 20, resizable: true, sortable: false, hidden : true  },
		            { name: 'option', index: 'option', width: 60, resizable: true, sortable: false }
				  ],
		rowNum: 20,
        rowList: [20, 30, 50],
        rownumbers: true,
        rownumWidth: 50,
        prmNames: { search: "search", page: "pageNo", rows: "limit" },
        height: 'auto',
        width: false,
        autowidth:true,
        editurl: '',
        viewrecords: true,
        cellEdit: false,
        shrinkToFit: true,
        grouping: false,
        postData:postData,
        jsonReader: {
            root: "items", //结果集
            records: "total", //总记录数 
            total: "pageCount", //总页数
            page: "pageNo", //当前页 
            repeatitems: false // (4) 
        },  
		multiselect:true,
		pager: "#estimateListPage",					
		viewrecords: true,
		hidegrid: false, 
		gridComplete: function(){
			var ids = $estimateList.jqGrid('getDataIDs');
			for(var i=0;i < ids.length;i++){
				var rowId = ids[i];
				var rowData = $estimateList.jqGrid('getRowData', ids[i]);
				var prjsname = rowData.prjsname;
				var reportTime = rowData.reportTime;
				var prjCode = rowData.prjCode;
				var todoStatus =rowData.todoStatus;
				/*var isEstimateDataNm = rowData.isEstimateDataNm;
				var isEstimateFileNm = rowData.isEstimateFileNm;*/
				var estimateId = rowData.estimateId;
				var noFile = rowData.noFile;
				var params = {
						/*'esDataUpload'	:	'estimateDataUploadTemp',*/
						'esData'    : 	'estimateDataTemp',
						'esFileUpload'	:	'estimateFileUploadTemp',
						'esFile'	:	'estimateFileTemp'
					};
					
				var permissionButton = Permission_Button.configPermissionButton(params);
				//permissionButton.esDataUpload = Permission_Button.clickPermissionButton('estimateDataUploadTemp',"ESTIMATE_INFO.estimateUpload('estimateData',\'"+prjsname+"\',\'"+reportTime+"\',\'"+prjCode+"\',\'"+estimateId+"\');");//估值材料上传
				//材料下载：材料已上传、材料已确认、已完成时可操作
				if(('C' == todoStatus || 'S' == todoStatus || 'E' == todoStatus) && 'N' == noFile){
					permissionButton.esData = Permission_Button.clickPermissionButton('estimateDataTemp',"ESTIMATE_INFO.attachDownload('" + estimateId + "','ESTIMATE_DATA');");
				}
				//产出上传：材料已确认时可操作
				if('C' == todoStatus){
					permissionButton.esFileUpload = Permission_Button.clickPermissionButton('estimateFileUploadTemp',"ESTIMATE_INFO.estimateUpload(\'"+estimateId+"\');");//估值文件上传
				}
				//产出下载：已完成时可操作
				if('E' == todoStatus){
					permissionButton.esFile = Permission_Button.clickPermissionButton('estimateFileTemp',"ESTIMATE_INFO.attachDownload('" + estimateId + "','ESTIMATE_FILE');");
				}
				$estimateList.jqGrid('setRowData', ids[i], { option: Permission_Button.linkAllBtn(permissionButton)});
			}	
		}
	});
	$estimateList.navGrid('#estimateListPage',{edit:false,add:false,del:false,search:false,refreshstate:'current'});
	$estimateList.jqGrid('setFrozenColumns');
	jqGridResize($estimateList);
	parameter ? queryByCondtion(true, parameter) : queryByCondtion(true);
};

function queryByCondtion(flag,parameter) {
	 if(parameter) {
	    	var paramJson = eval("(" + parameter + ")");
	    	var type = paramJson.type;
	    	var reportFrequency = paramJson.reportFrequency;
	    	var isEstimate = paramJson.isEstimate;
	    	//1当日，2本周，3本月
	    	if("1" == reportFrequency){
	    		var beginDate = formatDate(now);
	    		var endDate = formatDate(now);
	    		var newDate = beginDate + " - " +endDate;
	    		$("#q-reportTime").val(newDate);
	    	}else if("2" == reportFrequency){
	    		var beginDate = getWeekStartDate();
	    		var endDate = getWeekEndDate();
	    		var newDate = beginDate + " - " +endDate;
	    		$("#q-reportTime").val(newDate);
	    	}else if("3" == reportFrequency){
	    		var beginDate = getMonthStartDate();
	    		var endDate = getMonthEndDate();
	    		var newDate = beginDate + " - " +endDate;
	    		$("#q-reportTime").val(newDate);
	    	}
	    	if("ESTIMATE_DATA" == type){
	    		//$("#q-isEstimateData").val(isEstimate).trigger('change');
	    		if(isEstimate == '1'){//已上传
	    			$(".todoStatus").each(function(){
	    				if($(this).attr("value") == 'E' || $(this).attr("value")  == 'C' || $(this).attr("value")  == 'S'){
	    					$(this).removeClass('fa-square');
	    		    		$(this).addClass('fa-check-square');
	    				}
	    			});
	    		}else if(isEstimate == '0'){//未上传
	    			$(".todoStatus").each(function(){
	    				if($(this).attr("value") == 'R'||$(this).attr("value") == 'I'){
	    					$(this).removeClass('fa-square');
	    		    		$(this).addClass('fa-check-square');
	    				}
	    			});
	    		}
	    	}else if("ESTIMATE_FILE" == type){
	    		//$("#q-isEstimateFile").val(isEstimate).trigger('change');
	    		if(isEstimate == '1'){//已上传
	    			$(".todoStatus").each(function(){
	    				if($(this).attr("value") == 'E'){
	    					$(this).removeClass('fa-square');
	    		    		$(this).addClass('fa-check-square');
	    				}
	    			});
	    		}else if(isEstimate == '0'){//未上传
	    			$(".todoStatus").each(function(){
	    				if($(this).attr("value") != 'E'){
	    					$(this).removeClass('fa-square');
	    		    		$(this).addClass('fa-check-square');
	    				}
	    			});
	    		}
	    	}
	    	
	    }
	var postData = $estimateList.jqGrid("getGridParam", "postData");
	console.log(postData);
	var prjsname = $("#q-prjsname").val().trim();
	var outerId = $("#q-outerId").val().trim();
	//var reportTime = $("#q-reportTime").val();
	
	var beginReportTime = $("#q-reportTime").getDateRangeValue()[0];
	var endReportTime = $("#q-reportTime").getDateRangeValue()[1];
	
	var beginEndTime = $("#q-endTime").getDateRangeValue()[0];
	var endEndTime = $("#q-endTime").getDateRangeValue()[1];
	
	var beginUploadTime = $("#q-uploadTime").getDateRangeValue()[0];
	var endUploadTime = $("#q-uploadTime").getDateRangeValue()[1];
	var todoStatus = $("#q-todoStatus").val();
	
	/*var isEstimateData = $("#q-isEstimateData").val();
	var estimateDataTime = $("#q-estimateDataTime").val();
	var isEstimateFile = $("#q-isEstimateFile").val();
	var estimateFileTime = $("#q-estimateFileTime").val();*/
	var todoStatus = getChosen('todoStatus');
    $.extend(postData, {
        'sp[prjsname]':prjsname,
        'sp[outerId]':outerId,
        'sp[beginReportTime]':beginReportTime,
        'sp[endReportTime]':endReportTime,
        'sp[beginEndTime]':beginEndTime,
        'sp[endEndTime]':endEndTime,
        'sp[beginUploadTime]':beginUploadTime,
        'sp[endUploadTime]':endUploadTime,
        'sp[todoStatus]':todoStatus
        
    });
    if (flag) {
    	$estimateList.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid",[{page:1}]);//重新载入Grid表格
    } else {
    	$estimateList.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid");//重新载入Grid表格
    }
};

//绑定回车事件,查询
$("body").keypress(function(event){
	var key = event.which;
	if(key == "13"){
		queryByCondtion(true);
	}
});

//获得本周的开始日期 
function getWeekStartDate() { 
var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek+1); 
return formatDate(weekStartDate); 
} 

//获得本周的结束日期 
function getWeekEndDate() { 
var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek)+1); 
return formatDate(weekEndDate); 
} 

//获得本月的开始日期 
function getMonthStartDate(){ 
var monthStartDate = new Date(nowYear, nowMonth, 1); 
return formatDate(monthStartDate); 
} 

//获得本月的结束日期 
function getMonthEndDate(){ 
var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth)); 
return formatDate(monthEndDate); 
}
//格式化日期：yyyy-MM-dd 
function formatDate(date) { 
var myyear = date.getFullYear(); 
var mymonth = date.getMonth()+1; 
var myweekday = date.getDate(); 

if(mymonth < 10){ 
mymonth = "0" + mymonth; 
} 
if(myweekday < 10){ 
myweekday = "0" + myweekday; 
} 
return (myyear+"/"+mymonth + "/" + myweekday); 
}
//获得某月的天数 
function getMonthDays(myMonth){ 
var monthStartDate = new Date(nowYear, myMonth, 1); 
var monthEndDate = new Date(nowYear, myMonth + 1, 1); 
var days = (monthEndDate - monthStartDate)/(1000 * 60 * 60 * 24); 
return days; 
}
//是否选中(样式切换)
function initChoose(att){
    $('.'+att).on('click', function () {
    	var attr = $(this).attr("class");
    	if(attr.indexOf("fa-square") > -1){
    		$(this).removeClass('fa-square');
    		$(this).addClass('fa-check-square');
		}else{
			$(this).removeClass('fa-check-square');
    		$(this).addClass('fa-square');
		}
	});
}

//获取选中的值
function getChosen(element){
	var data = '';
	//遍历
    $('.'+element+'.fa-check-square').each(function(index,element){
    	data += $(element).attr("value")+',';
    });
   /* if(data.length > 0){
    	data = data.substr(0,data.length-1);
    }*/
    return data;
}
function clears(){
	$(".todoStatus").each(function(){
		var attr = $(this).attr("class");
    	if(attr.indexOf("fa-check-square") > -1){
    		$(this).removeClass('fa-check-square');
    		$(this).addClass('fa-square');
		}
	});
}